/*
RetroLeague - Mobile application for The Retro League Podcast
Copyright (C) 2010-2013 Hugues Johnson

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software 
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

package com.huguesjohnson.retroleague;

import java.io.File;

import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.huguesjohnson.retroleague.util.SerializationHelper;
import com.huguesjohnson.retroleague.util.Utils;

public class ViewEntryActivity extends SherlockActivity{
	private final static String TAG="ViewEntryActivity";
	private boolean hasDownload=false;
	//extra info
	private boolean extraInfoShowLink=false;
	private boolean extraInfoRenderContent=false;
	//menu constants
	private final static int MENU_BACK=0;
	private final static int MENU_SHARE=1;
	//components that need to be accessible
	private Button saveButton;
	private Button playButton;
	
	private class SaveFileTask extends AsyncTask<String,Integer,Void>{
		@Override
		protected void onPreExecute(){
			try{
				saveButton.setClickable(false);
				saveButton.setEnabled(false);
			}catch(Exception x){
				Log.e(TAG,"SaveEpisodeTask.onPreExecute",x);
			}		
		}

		@Override
		protected Void doInBackground(String... params){
			try{
				StreamEntry entry=StreamActivity.getSelectedEntry();
				int enclosureLength=entry.getDownloadLength();
				if(SerializationHelper.checkMediaState()){
					String fileName=entry.getDownloadFileName();
					Log.d(TAG,"DownloadEpisodeTask.doInBackground - fileName="+fileName);
					String downloadDir=Utils.getDownloadPath();
					File destinationDir=new File(downloadDir);
					if(!destinationDir.exists()){
						boolean success=destinationDir.mkdirs();
						Log.d(TAG,"DownloadEpisodeTask.doInBackground - result of destinationDir.mkdirs() is "+success);
					}
					String downloadPath=downloadDir+"/"+fileName;
					Log.d(TAG,"DownloadEpisodeTask.doInBackground - downloadPath="+downloadPath);	
					Intent downloadEpisodeIntent=new Intent(getApplicationContext(),DownloadEpisodeIntentService.class);
					downloadEpisodeIntent.putExtra("downloadPath",downloadPath);
					downloadEpisodeIntent.putExtra("episodeTitle",entry.getTitle());
					downloadEpisodeIntent.putExtra("enclosureLength",enclosureLength);
					downloadEpisodeIntent.putExtra("downloadUrl",entry.getDownloadUrl());
					startService(downloadEpisodeIntent);
				}else{
					throw(new Exception("SerializationHelper.checkMediaState() is false"));
				}
			}catch(Exception x){
				Log.e(TAG,"SaveEpisodeTask.doInBackground",x);
				showErrorDialog(x);	
			}
			return(null);
		}
	}	
	
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        try{
        	//setup actionbar
        	ActionBar actionBar=getSupportActionBar();
        	actionBar.setIcon(R.drawable.logo); 
        	actionBar.setTitle("");
        	//get extra info
        	this.extraInfoRenderContent=this.getIntent().getExtras().getBoolean("extraInfoRenderContent",false);
        	this.extraInfoShowLink=this.getIntent().getExtras().getBoolean("extraInfoShowLink",false);
        	//load the view
        	this.setContentView(R.layout.entrylanding);
			final StreamEntry entry=StreamActivity.getSelectedEntry();
			if(entry==null){
				//go back to the main activity
				this.finish();
			}
			//content
			WebView content=(WebView)findViewById(R.id.entrylanding_content);
			content.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
			if(extraInfoRenderContent){
				String contentEncoded=entry.getContent();
				Log.d("contentEncoded",contentEncoded);
	            content.loadDataWithBaseURL("",contentEncoded,"text/html","UTF-8","");
			}else{
	            content.loadUrl(entry.getUrl());
			}
            //save and play
        	this.saveButton=(Button)findViewById(R.id.entrylanding_savebutton);
        	this.playButton=(Button)findViewById(R.id.entrylanding_playbutton);
            String downloadUrl=entry.getDownloadUrl();
            if((downloadUrl==null)||(downloadUrl.length()<1)){
            	this.hasDownload=false;
            	this.playButton.setVisibility(View.GONE);
            	this.saveButton.setVisibility(View.GONE);
            	TextView saveLabel=(TextView)findViewById(R.id.entrylanding_savelabel);
            	saveLabel.setVisibility(View.GONE);
            }else{
            	this.hasDownload=true;
            	this.saveButton.setText(entry.getDownloadFileName());
            	this.playButton.setText(entry.getDownloadFileName());
            	this.saveButton.setOnClickListener(
            			new OnClickListener(){
            				@Override
            				public void onClick(View v){
            		    		try{
            		    			new SaveFileTask().execute("");
            		    		}catch(Exception x){
            		    			Log.e(TAG,"downloadButtonListener",x);
            		    			showErrorDialog(x);
            		    		}
            		    	}
            		    } );
            	this.playButton.setOnClickListener(
            			new OnClickListener(){
            				@Override
            				public void onClick(View v){
            		    		try{
            		    			String downloadDir=Utils.getDownloadPath();
            		    			String fileName=entry.getDownloadFileName();
            		    			String filePath=downloadDir+"/"+fileName;
            		    			Intent intent=new Intent(Intent.ACTION_VIEW);
            		    			Uri uri=Uri.parse("file:///"+filePath);
            		    			intent.setDataAndType(uri,"audio/*");
            		    			startActivity(intent);
            		    		}catch(Exception x){
            		    			Log.e(TAG,"playButtonListener",x);
            		    			showErrorDialog(x);
            		    		}
            		    	}
            		    } );
            }
			//link
        	Button linkButton=(Button)findViewById(R.id.entrylanding_linkbutton);
            final String linkUrl=entry.getUrl();
            if((this.extraInfoShowLink)&&(linkUrl!=null)&&(linkUrl.length()>1)){
            	linkButton.setVisibility(View.VISIBLE);
            	linkButton.setText(linkUrl);
            	linkButton.setOnClickListener(
            			new OnClickListener(){
            				@Override
            				public void onClick(View v){
            		    		try{
            		    			Intent browserIntent=new Intent(Intent.ACTION_VIEW,Uri.parse(linkUrl));
            		    			startActivity(browserIntent);
            		    		}catch(Exception x){
            		    			Log.e(TAG,"linkButtonListener",x);
            		    			showErrorDialog(x);
            		    		}
            		    	}
            		    } );
            }else{
            	linkButton.setVisibility(View.GONE);
            	TextView linkLabel=(TextView)findViewById(R.id.entrylanding_linklabel);
            	linkLabel.setVisibility(View.GONE);            	
            } 
		}catch(Exception x){
			Log.e(TAG,"onCreate");
			showErrorDialog(x);
		}
    }	
	
    @Override
    protected void onResume(){
		super.onResume();
		try{
			//check if the file has already been downloaded or is downloading
			if(this.hasDownload){
				this.saveButton.setEnabled(true);
				this.saveButton.setClickable(true);
				boolean isDownloaded=false;
				boolean isDownloading=false;
				File f=null;
				StreamEntry entry=StreamActivity.getSelectedEntry();
				int enclosureLength=entry.getDownloadLength();
				String fileName=entry.getDownloadFileName();
				String downloadDir=Utils.getDownloadPath();
				File destinationDir=new File(downloadDir);
				if(destinationDir.exists()){
					String filePath=downloadDir+"/"+fileName;
					f=new File(filePath);
					if(f.exists()){
						if(f.length()>=enclosureLength){
							isDownloaded=true;
						}
					}else{
						filePath=downloadDir+"/"+fileName+".partial";
						f=new File(filePath);
						if(f.exists()){
							isDownloading=true;
						}
					}
				}
				if(isDownloaded){
					this.saveButton.setVisibility(View.GONE);
					if(Utils.isMediaFile(fileName)){
						this.playButton.setVisibility(View.VISIBLE);
					}else{
						this.playButton.setVisibility(View.GONE);
					}
				}else if(isDownloading){
					this.playButton.setVisibility(View.GONE);
					this.saveButton.setVisibility(View.VISIBLE);
					this.saveButton.setEnabled(false);
					this.saveButton.setClickable(false);
				}else{
					this.playButton.setVisibility(View.GONE);
					this.saveButton.setVisibility(View.VISIBLE);
					this.saveButton.setEnabled(true);
					this.saveButton.setClickable(true);
				}
			}else{//no download
				this.playButton.setVisibility(View.GONE);
				this.saveButton.setVisibility(View.GONE);
			}
		}catch(Exception x){
			Log.e(TAG,"onResume",x);
		}    	
    }
    
	@Override
	public boolean onCreateOptionsMenu(Menu menu){
		try{
			menu.add(0,MENU_BACK,MENU_BACK,"Back to stream").setIcon(R.drawable.menu_back);
			StreamEntry entry=StreamActivity.getSelectedEntry();
			if(entry!=null){
				menu.add(0,MENU_SHARE,MENU_SHARE,"Share").setIcon(R.drawable.menu_share);
			}
			return(true);
		}catch(Exception x){
			Log.e(TAG,"onCreateOptionsMenu",x);
			return(false);
		}
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item){
		try{
			switch(item.getItemId()){
				case MENU_BACK:{this.finish();return(true);}
				case MENU_SHARE:{
					try{
						StreamEntry entry=StreamActivity.getSelectedEntry();
						if(entry==null){
							Log.e(TAG,"onOptionsItemSelected: entry is null"+item.getItemId());
							return(false);
						}
						Intent shareIntent=new Intent(android.content.Intent.ACTION_SEND);				
						shareIntent.setType("text/plain");
						shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,entry.getTitle());
						shareIntent.putExtra(android.content.Intent.EXTRA_TEXT,entry.getTitle()+" "+entry.getUrl());
						startActivity(Intent.createChooser(shareIntent,"Share via"));
					}catch(Exception x){
						Log.e(TAG,"onOptionsItemSelected - case MENU_SHARE",x);
						return(false);
					}
					return(true);
				}
			default:{return(false);}
			}
		}catch(Exception x){
			if(item!=null){
				Log.e(TAG,"onOptionsItemSelected: item.getItemId()="+item.getItemId(),x);
			}else{
				Log.e(TAG,"onOptionsItemSelected: item is null",x);
			}
			return(false);
		}
	}    

	private void showErrorDialog(Exception x){
		try{
	        new AlertDialog.Builder(this)
	   		.setTitle(R.string.app_name)
	   		.setMessage("Error: "+x.getMessage())
	   		.setPositiveButton("Close", null)
	   		.show();	
		}catch(Exception reallyBadTimes){
			Log.e(TAG,"showErrorDialog",reallyBadTimes);
		}
	}
}